<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">





  <link rel="alternate" href="/atom.xml" title="renhao" type="application/atom+xml">






<meta name="description" content="在项目中有时由于业务需求进行了大量的if-else判断，如何减少他们。本文学习于教程">
<meta property="og:type" content="article">
<meta property="og:title" content="重构大量if...else">
<meta property="og:url" content="https://huangrenhao.gitee.io/2019/10/07/js-if-else/index.html">
<meta property="og:site_name" content="renhao">
<meta property="og:description" content="在项目中有时由于业务需求进行了大量的if-else判断，如何减少他们。本文学习于教程">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-09-03T08:50:37.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="重构大量if...else">
<meta name="twitter:description" content="在项目中有时由于业务需求进行了大量的if-else判断，如何减少他们。本文学习于教程">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://huangrenhao.gitee.io/2019/10/07/js-if-else/">





  <title>重构大量if...else | renhao</title>
  








<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">
  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">renhao</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://huangrenhao.gitee.io/2019/10/07/js-if-else/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="renhao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="renhao">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">重构大量if...else</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-10-07T11:55:48+08:00">
                2019-10-07
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/js/" itemprop="url" rel="index">
                    <span itemprop="name">js</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/10/07/js-if-else/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/10/07/js-if-else/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.1k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  5
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>在项目中有时由于业务需求进行了大量的if-else判断，如何减少他们。本文学习于<a href="https://juejin.im/post/5cfb0359e51d4556d86c7a8d" target="_blank" rel="noopener">教程</a><a id="more"></a></p>
<p>对于我来说我只能想到使用switch+case解决方式，实际上还有很多的优秀方法。</p>
<p>需要重构程序：</p>
<pre><code>/**
 * 初始化函数
 * if...else if... 的情况较为简单
 * @return undefined
 */
function init () {
    // 是否回答过题目 1-回答过, 通过 2-回答过, 没有通过 3-没有回答过
    let isAnswer
    // 是否是老用户 1-老用户 2-新用户
    let isOldUser

    if (isAnswer === 1) {
        // ...
    } else if (isAnswer === 2) {
        // ...
    } else if (isAnswer === 3) {
        // ...
    }

    if (isOldUser === 1) {
        // ...
    } else if (isOldUser === 2) {
        // ...
    }
}
</code></pre><pre><code>/**
 * 初始化函数
 * if...else if... 嵌套的情况
 * @return undefined
 */
function init () {
    if (isAnswer === 1) {
        if (isOldUser === 1) {
            // ...
        } else if (isOldUser === 2) {
            // ...
        }
    } else if (isAnswer === 2) {
        if (isOldUser === 1) {
            // ...
        } else if (isOldUser === 2) {
            // ...
        }
    } else if (isAnswer === 3) {
        if (isOldUser === 1) {
            // ...
        } else if (isOldUser === 2) {
            // ...
        }
    }
}
</code></pre><h3 id="查找表"><a href="#查找表" class="headerlink" title="查找表"></a>查找表</h3><pre><code>// 可以解决if...else if...简单的问题
const rules = {
    isAnswer1 () {
        return code
    },
    isAnswer2 () {
        return code
    },
    isAnswer3 () {
        return code
    }
}

function determineAction (type) {
    if (isAnswer === 1) {
        return &#39;isAnswer1&#39;
    } else if (isAnswer === 2) {
        return &#39;isAnswer2&#39;
    } else if (isAnswer === 3) {
        return &#39;isAnswer3&#39;
    }
}

function init () {
    let key = determineAction(isAnswer)
    return rules[key]
}
</code></pre><pre><code>// 面对if...else if...else 嵌套的复杂情况

const rules = [
    {
        match (an, old) {
            if (an === 1) {
                return true
            }
        },

        action (an, old) {
            if (old === 1) {
                // ...
            } else if (old === 2) {
                // ...
            }
        }
    },
    {
        match (an, old) {
            if (an === 2) {
                return true
            }
        },

        action (an, old) {
            if (old === 1) {
                // ...
            } else if (old === 2) {
                // ...
            }
        }
    },
    {
        match (an, old) {
            if (an === 3) {
                return true
            }
        },

        action (an, old) {
            if (old === 1) {
                // ...
            } else if (old === 2) {
                // ...
            }
        }
    }
]

function init (an, old) {
    for (let i = 0; i &lt; rules.length; i++) {
        // 如果返回true
        if (rules[i].match(an, old)) {
            rules[i].action(an, old)
        }
    }
}

init(isAnswer, isOldUser)
</code></pre><p>实际上只是做了一层封装，实际上结构上还是充斥了if-else，只是将init函数的复杂度降低。</p>
<h3 id="面向切片的编程（AOP）"><a href="#面向切片的编程（AOP）" class="headerlink" title="面向切片的编程（AOP）"></a>面向切片的编程（AOP）</h3><blockquote>
<p>AOP，aspect-oriented programming（面向方面/切片编程），通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。利用AOP可以对业务逻辑的各个部分进行隔离，使得业务逻辑各部分之间的耦合度降低，提高程序的可重用性与开发效率。<a href="https://baike.baidu.com/item/AOP/1332219?fromtitle=%E9%9D%A2%E5%90%91%E5%88%87%E9%9D%A2%E7%BC%96%E7%A8%8B&amp;fromid=6016335" target="_blank" rel="noopener">百度百科</a></p>
</blockquote>
<p>为Function的原型链扩展after语法，如果满足要求直接在函数内运算并返回结果，如果不满足条件返回’next’调用职责链的下一个节点。</p>
<pre><code>// 可以解决if...else if...简单的问题
// Function.prototype.after是在本函数执行前执行after添加的函数
Function.prototype.after = function (nextFn) { 
    let self = this
    return function (...rest) {
        let code = self(...rest)
        if (code === &#39;next&#39;) {
            return nextFn(...rest)
        }
        return code
    }
}

// 重构原函数

function isAnswer1 (type) {
    if (type === 1) {
        return code
    }
    return &#39;next&#39;
}

function isAnswer2 (type) {
    if (type === 2) {
        return code
    }
    return &#39;next&#39;
}

function isAnswer3 (type) {
    if (type === 3) {
        return code
    }
    return &#39;next&#39;
}
// 执行顺序仍然是isAnswer1-&gt;isAnswer2-&gt;isAnswer3
let isAnswerFn = isAnswer1.after(isAnswer2).after(isAnswer3)

isAnswerFn(isAnswer)
</code></pre><pre><code>// 面对if...else if...else 嵌套的复杂情况

function isAnswer1 (an, old) {
    if (an === 1) {
        return isOldUserFn1(an, old)
    }
    return &#39;next&#39;
}

function isAnswer2 (an, old) {
    if (an === 2) {
        return isOldUserFn2(an, old)
    }
    return &#39;next&#39;
}

function isAnswer3 (an, old) {
    if (an === 3) {
        return isOldUserFn3(an, old)
    }
    return &#39;next&#39;
}

/**
 * isAnswer == 1 isOldUser == 1 的情况
 */
function isAnswer1IsOldUser1 (an, old) {
    if (old === 1) {
        return code
    }
    return &#39;next&#39;
}

/**
 * isAnswer == 1 isOldUser == 2 的情况
 */
function isAnswer1IsOldUser2 (an, old) {
    if (old === 2) {
        return code
    }
    return &#39;next&#39;
}

/**
 * isAnswer == 2 isOldUser == 1 的情况
 */
function isAnswer2IsOldUser1 (an, old) {
    if (old === 1) {
        return code
    }
    return &#39;next&#39;
}

/**
 * isAnswer == 2 isOldUser == 2 的情况
 */
function isAnswer2IsOldUser2 (an, old) {
    if (old === 2) {
        return code
    }
    return &#39;next&#39;
}

/**
 * isAnswer == 3 isOldUser == 1 的情况
 */
function isAnswer3IsOldUser1 (an, old) {
    if (old === 1) {
        return code
    }
    return &#39;next&#39;
}

/**
 * isAnswer == 3 isOldUser == 2 的情况
 */
function isAnswer3IsOldUser2 (an, old) {
    if (old === 2) {
        return code
    }
    return &#39;next&#39;
}

let isAnswerFn = isAnswer1.after(isAnswer2).after(isAnswer3)

// 三条职责链
let isOldUserFn1 = isAnswer1IsOldUser1.after(isAnswer1IsOldUser2)
let isOldUserFn2 = isAnswer2IsOldUser1.after(isAnswer2IsOldUser2)
let isOldUserFn3 = isAnswer3IsOldUser1.after(isAnswer3IsOldUser2)

isAnswerFn(isAnswer, isOldUser)
</code></pre><h3 id="函数式编程"><a href="#函数式编程" class="headerlink" title="函数式编程"></a>函数式编程</h3><pre><code>import R from &#39;ramda&#39;

var fn = R.cond([
  [R.equals(0),   R.always(&#39;water freezes at 0°C&#39;)],
  [R.equals(100), R.always(&#39;water boils at 100°C&#39;)],
  [R.T,           temp =&gt; &#39;nothing special happens at &#39; + temp + &#39;°C&#39;]
]);

fn(0); //=&gt; &#39;water freezes at 0°C&#39;
fn(50); //=&gt; &#39;nothing special happens at 50°C&#39;
fn(100); //=&gt; &#39;water boils at 100°C&#39;
</code></pre><blockquote>
<p><a href="http://ramda.cn/docs/#cond" target="_blank" rel="noopener">ramda</a>，cond返回一个封装了<code>if/else,if/else,...</code>逻辑的函数<code>fn</code>。<code>R.cond</code>接受列表元素为[predicate,transformer]的列表。<code>fn</code>的所有参数顺次作用于每个predicate，直到有一个返回<code>truthy</code>值，此时相应transformer对参数处理并作为<code>fn</code>的结果返回，如果没有predicate匹配，则<code>fn</code>返回undefined。</p>
<p><code>R.always</code>返回一个返回恒定值的函数，对于非原始值返回的值是对原始值的引用。</p>
<p><code>R.equals</code>如果传入的参数相等，返回<code>true</code>否则返回<code>false</code>。</p>
</blockquote>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/10/07/css3-new/" rel="next" title="css3新特性与动画">
                <i class="fa fa-chevron-left"></i> css3新特性与动画
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/10/15/webpack-bale-tree-shaking/" rel="prev" title="Tree-Shaking">
                Tree-Shaking <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">renhao</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">94</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#查找表"><span class="nav-number">1.</span> <span class="nav-text">查找表</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#面向切片的编程（AOP）"><span class="nav-number">2.</span> <span class="nav-text">面向切片的编程（AOP）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#函数式编程"><span class="nav-number">3.</span> <span class="nav-text">函数式编程</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">renhao</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">265.9k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '2P1xqUWiCoNm14MH4yhURlJi-gzGzoHsz',
        appKey: 'uJN0uagHIVgXtBO1OuLV9Ban',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  

  

  
  

  

  

  

</body>
</html>
